/*
 *  Copyright 2011 Eduardo H. Bogoni <eduardobogoni@gmail.com>.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package net.stuffrepos.bricknetcenter.util.validation;

/**
 *
 * @author Eduardo H. Bogoni <eduardobogoni@gmail.com>
 */
public class StringConstraint implements Constraint<String> {

    public static final int DEFAULT_MIN_LENGTH = 0;
    public static final int DEFAULT_MAX_LENGTH = 255;
    private final boolean required;
    private final int minLength;
    private final int maxLength;

    public StringConstraint(boolean required, Integer minLength, Integer maxLength) {
        this.required = required;
        this.minLength = (minLength == null ? DEFAULT_MIN_LENGTH : minLength);
        this.maxLength = (maxLength == null ? DEFAULT_MAX_LENGTH : maxLength);
    }

    @Override
    public boolean isValid(String value) {
        if (value != null) {
            value = value.trim();
            if (value.isEmpty()) {
                value = null;
            }
        }

        if (value == null && required) {
            return false;
        }

        if (value != null && value.length() < getMinLength()) {
            return false;
        }

        if (value != null && value.length() > maxLength) {
            return false;
        }

        return true;
    }

    public int getMaxLength() {
        return maxLength;
    }

    public int getMinLength() {
        return minLength;
    }
}
